import React, { useState, useEffect } from 'react';
import styles from './index.less';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import {
  Button,
  Modal,
  Table,
  Tooltip,
  Select,
  Form,
  Row,
  Col,
  Input,
  DatePicker,
} from 'antd';
import moment from 'moment';
import xlsx from 'xlsx';
import util from '@/compontents/util.js';
import handleOrder from '../handleOrder';
const { confirm } = Modal;
const { Option } = Select;
const { RangePicker } = DatePicker;

const { uOrderBusList, uSchoolManageList, uOrderToPay, handleAccount } = api;
export default (props: any) => {
  const { manageId, schoolId, userName } = JSON.parse(
    sessionStorage.info,
  ).userInfo;
  const columns: any = [
    {
      title: '订单号',
      dataIndex: 'orderNum',
      width: 180,
    },
    {
      title: '券码',
      dataIndex: 'ticketCode',
      width: 180,
    },
    {
      title: '订单价格（元）',
      dataIndex: 'price',
      width: 120,
    },
    {
      title: '腾讯扣除平台费(元）',
      dataIndex: 'priceWX',
      width: 150,
    },
    {
      title: '商家分账金额（元）',
      dataIndex: 'priceSplit',
      width: 150,
    },
    {
      title: '商家分账比例（%）',
      dataIndex: 'priceScale',
      width: 150,
    },
    {
      title: '商户号入账金额(元）',
      dataIndex: 'priceUni',
      width: 150,
    },
    {
      title: '券数量',
      dataIndex: 'ticketNum',
      width: 100,
    },
    {
      title: '券状态',
      dataIndex: 'status',
      render: (v1: any, v2: any) => <div>{formatStatus(v2.status)}</div>,
      width: 120,
    },
    {
      title: '商铺',
      dataIndex: 'uBusinessId',
      ellipsis: {
        showTitle: false,
      },
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={formatSchool(v2.businessManageId)}>
          {formatSchool(v2.businessManageId)}
        </Tooltip>
      ),
      width: 150,
    },
    {
      title: '商家电话',
      dataIndex: 'telBusi',
      width: 120,
    },
    {
      title: '商家姓名',
      dataIndex: 'nameBusi',
      width: 120,
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={v2.nameBusi}>
          {v2.nameBusi}
        </Tooltip>
      ),
    },
    {
      title: '用户电话',
      dataIndex: 'telUser',
      width: 120,
    },
    {
      title: '用户昵称',
      dataIndex: 'nameUser',
      width: 120,
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={v2.nameUser}>
          {v2.nameUser}
        </Tooltip>
      ),
    },
    {
      title: '订单备注',
      dataIndex: 'remark',
      width: 150,
      ellipsis: {
        showTitle: false,
      },
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={v2.remark}>
          {v2.remark}
        </Tooltip>
      ),
    },
    {
      title: '下单时间',
      dataIndex: 'time',
      ellipsis: {
        showTitle: false,
      },
      width: 180,
      render: (v1: any, v2: any) => (
        <Tooltip placement="topLeft" title={util.formatTime(v2.time)}>
          {util.formatTime(v2.time)}
        </Tooltip>
      ),
    },
    // {
    //   title: '订单关闭时间',
    //   dataIndex: 'endTime',
    //   ellipsis: {
    //     showTitle: false,
    //   },
    //   width: 180,
    //   render: (v1: any, v2: any) => (
    //     <Tooltip placement="topLeft" title={util.formatTime(v2.endTime)}>
    //       {util.formatTime(v2.endTime)}
    //     </Tooltip>
    //   ),
    // },

    {
      title: '操作',
      dataIndex: 'handle',
      width: 230,
      fixed: 'right',
      render: (v1: any, v2: any) => (
        <div>
          <Button
            style={{ marginRight: 10 }}
            disabled={v2.status !== 4}
            onClick={() => {
              handAccout(v2);
            }}
            size="small"
            type="primary"
          >
            手动分账
          </Button>
          <Button
            disabled={v2.status !== 3}
            onClick={() => {
              payReturn(v2);
            }}
            size="small"
            type="primary"
            danger
          >
            退款
          </Button>
        </div>
      ),
    },
  ];
  const [list, setList] = useState([]);
  const [total, setTotal] = useState(0);

  // 学校列表
  const [schoolList, setSchoolList]: any = useState([]);
  const payReturn = (item: any) => {
    const { id } = item;
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定退款吗？',
      onOk() {
        uOrderToPay({ id }).then(res => {
          const _filData = { ...filData };
          _filData.pageNo = 1;
          _filData.pageSize = 10;
          getList(_filData);
        });
      },
    });
    //
  };

  // 订单状态列表
  const statusList = [
    {
      id: 3,
      name: '已支付未使用',
    },
    {
      id: 4,
      name: '已支付已使用',
    },
    {
      id: 5,
      name: '已退款',
    },
  ];
  // 商家列表
  const [businessManageId, setBusinessManageId] = useState(0);
  const [priceAll, setPriceAll] = useState('');
  const [priceSplitAll, setPriceSplitAll] = useState('');
  const [priceWXAll, setPriceWXAll] = useState('');
  const [priceUniAll, setPriceUniAll] = useState('');
  // 获取入驻学校列表
  const getSchoolList = () => {
    uSchoolManageList({
      pageNo: 1,
      pageSize: 100000,
      schoolId,
      type: 2,
    }).then((res: any) => {
      const { list, total } = res.data;
      console.log(list);
      setSchoolList(list);
    });
  };
  const formItemLayout = {
    labelCol: {
      xxl: {
        span: 6,
      },
      xl: {
        span: 8,
      },
    },
    wrapperCol: {
      xxl: {
        span: 18,
      },
      xl: {
        span: 16,
      },
    },
  };
  const [filData, setFilData] = useState({
    pageNo: 1,
    pageSize: 10,
    status: 0,
    businessManageId: 0,
    orderNum: '',
    startDate: '',
    endDate: '',
    uSchoolId: schoolId,
  });
  const getList = (data: any) => {
    uOrderBusList(data).then((res: any) => {
      const { list, total } = res.data;
      list.map((item: any, i: any) => {
        item.telBusi = item.uBusinessInfo.userName;
        item.nameBusi = item.uBusinessInfo.wxName;
        item.telUser = item.loginInfo.tel;
        item.nameUser = item.loginInfo.nickName;
        item.price = parseFloat(item.price).toFixed(2);
        item.priceWX = (Math.round(item.price * 0.6) / 100).toFixed(2);
        item.priceSplit =
          item.status === 4
            ? (
                parseInt(item.price * item.uBusinessInfo.scale + '') / 100
              ).toFixed(2)
            : '--';
        item.priceScale = item.status === 4 ? item.uBusinessInfo.scale : '--';
        item.priceUni =
          item.status === 4
            ? (
                item.price -
                Math.round(item.price * 0.6) / 100 -
                parseInt(item.price * item.uBusinessInfo.scale + '') / 100
              ).toFixed(2)
            : '--';
      });
      let [priceTotal, priceSplitTotal, priceWXTotal, priceUniTotal] = [
        0,
        0,
        0,
        0,
      ];
      list.map((item: any, i: any) => {
        const { price, priceSplit, priceWX, priceUni } = item;
        priceTotal += parseFloat(price);
        priceSplitTotal += parseFloat(priceSplit);
        priceWXTotal += parseFloat(priceWX);
        priceUniTotal += parseFloat(priceUni);
      });
      setPriceAll(priceTotal.toFixed(2));
      setPriceSplitAll(priceSplitTotal.toFixed(2));
      setPriceWXAll(priceWXTotal.toFixed(2));
      setPriceUniAll(priceUniTotal.toFixed(2));
      setList(list);
      setTotal(total);
    });
  };
  // 分页改变
  const pageChange = (pageNo2: any, pageSize2: any) => {
    const params = { ...filData };
    params.pageNo = pageNo2;
    params.pageSize = pageSize2;
    setFilData(params);
    getList(params);
  };

  const formatStatus = (id: any) => {
    if (statusList.length) {
      const name = statusList.filter((item: any) => item.id === id)[0].name;
      return name;
    }
  };
  const formatSchool = (id: any) => {
    const name = schoolList.filter((item: any) => item.manageId === id);
    return name.length ? name[0].name : '';
  };

  // 学校下拉列表改变
  const filChange1 = (e: any, v: any) => {
    const key = e ? v.key : 0;
    const params = { ...filData };
    params.businessManageId = parseInt(key);
    params.pageNo = 1;
    params.pageSize = 10;
    setFilData(params);
    getList(params);
  };
  // 下拉列表改变
  const filChange2 = (e: any) => {
    const params = { ...filData };
    params.status = e ? e : 0;
    params.pageNo = 1;
    params.pageSize = 10;
    setFilData(params);
    getList(params);
  };
  const filChange3 = (e: any) => {
    const params = { ...filData };
    params.orderNum = e.target.value;
    params.pageNo = 1;
    params.pageSize = 10;
    setFilData(params);
    getList(params);
  };

  const filChange4 = (e: any) => {
    const params = { ...filData };
    params.startDate = e ? moment(e[0]).format('YYYY-MM-DD HH:mm:ss') : '';
    params.endDate = e ? moment(e[1]).format('YYYY-MM-DD HH:mm:ss') : '';
    params.pageNo = 1;
    params.pageSize = 10;
    setFilData(params);
    getList(params);
  };

  const toExcel = () => {
    const jsono = util.xlsx.getGridDataToJson('#excel');
    util.xlsx.downloadExl(jsono, xlsx, 'order');
  };

  const handAccout = (item: any) => {
    const { ticketCode } = item;
    handleAccount({ ticketCode }).then(res => {
      Modal.success({
        title: '提示',
        content: JSON.stringify(res.data),
      });
    });
  };
  useEffect(() => {
    getList(filData);
    getSchoolList();
  }, []);
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <div className={styles.tool}>
          <Form hideRequiredMark={true}>
            <Row gutter={24} justify="start">
              <Col span={8}>
                <Form.Item label="选择商铺" {...formItemLayout}>
                  <Select
                    showSearch
                    placeholder="请选择商铺"
                    allowClear
                    onChange={filChange1}
                  >
                    {schoolList.map((item: any, i: any) => (
                      <Option key={item.manageId} value={item.name}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="订单状态" {...formItemLayout}>
                  <Select
                    placeholder="请选择订单状态"
                    allowClear
                    onChange={filChange2}
                  >
                    {statusList.map((item: any, i: any) => (
                      <Option key={item.id} value={item.id}>
                        {item.name}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              <Col span={8}>
                <Form.Item label="订单号" {...formItemLayout}>
                  <Input onChange={filChange3} placeholder="请输入订单号" />
                </Form.Item>
              </Col>
            </Row>
          </Form>
          <Form hideRequiredMark={true}>
            <Row gutter={24} justify="start">
              <Col span={8}>
                <Form.Item label="选择日期" {...formItemLayout}>
                  <RangePicker
                    style={{ width: 400 }}
                    onChange={filChange4}
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                  />
                </Form.Item>
              </Col>
              <Col span={8}></Col>
              <Col span={8}>
                <Form.Item colon={false} label=" " {...formItemLayout}>
                  <Button
                    onClick={() => {
                      toExcel();
                    }}
                    type="primary"
                  >
                    导出订单excel
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>

        {schoolList.length ? (
          <div>
            {filData.status === 4 && (
              <div className={styles.totalPrice}>
                <div>
                  订单价格合计：<span>{priceAll}</span> 元
                </div>
                <div>
                  腾讯扣除平台费合计：<span>{priceWXAll}</span> 元
                </div>
                <div>
                  商家分账金额合计：<span>{priceSplitAll}</span> 元
                </div>
                <div>
                  商户号入账金额合计：<span>{priceUniAll}</span> 元
                </div>
              </div>
            )}
            <Table
              className="oddTable"
              scroll={{ x: 1300 }}
              id="excel"
              dataSource={list}
              columns={columns}
              pagination={{
                showQuickJumper: true,
                total,
                defaultCurrent: filData.pageNo,
                defaultPageSize: filData.pageSize,
                size: 'small',
                onChange: pageChange,
                showTotal: () => {
                  return `总共 ${total} 条记录`;
                },
              }}
            />
          </div>
        ) : (
          <div></div>
        )}
      </div>
    </CardCommon>
  );
};
